package com.example.idlefish.MyAccount.activity

import android.animation.*
import android.annotation.*
import android.graphics.Color
import android.os.*
import android.util.Log
import androidx.activity.ComponentActivity
import com.example.idlefish.MyAccount.contract.MeFollowContract
import com.example.idlefish.MyAccount.pojo.*
import com.example.idlefish.MyAccount.pojo.Result
import com.example.idlefish.PublicModule.*
import com.example.idlefish.PublicModule.CommonUtil
import com.example.idlefish.PublicModule.UserConst.Companion.id
import com.example.idlefish.databinding.MyaccountOtherHomepageBinding
import com.fasterxml.jackson.databind.ObjectMapper
import com.google.gson.Gson
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import java.io.IOException

@SuppressLint("SetTextI18n")
class HomepageActivity : ComponentActivity() {
    private lateinit var binding: MyaccountOtherHomepageBinding
    private val client = OkHttpClient()
    private val mapper = ObjectMapper()
    private var signInId = 0
    private val handler = Handler(Looper.getMainLooper())
    private val mediaType = "application/json;charset=utf-8".toMediaTypeOrNull()
    private val message = Message()
    private var isFollow: Boolean = false
    private lateinit var userInfo: UserHomepageInfo

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        binding = MyaccountOtherHomepageBinding.inflate(layoutInflater)
        setContentView(binding.root)

        initInfo()

        // Log.i("主页信息", userInfo.toString())
         binding.follow.setOnClickListener {
            meFollowLauncher.launch(userInfo.id)
        }
        binding.fans.setOnClickListener{
            meFansLauncher.launch(userInfo.id)
        }

        binding.followButton.setOnClickListener {
            if (isFollow) {
                binding.followButton.text = "已关注"
            } else {
                binding.followButton.text = "关注"
            }
            isFollow = !isFollow
            // 切换背景颜色
          /*   val targetColor = if (isFollow) Color.RED else Color.BLUE
            ObjectAnimator.ofArgb(binding.followButton, "backgroundColor", targetColor).start()
        */
            // 切换字体颜色
            val targetColor = if (isFollow) Color.RED else Color.BLUE
            binding.followButton.setTextColor(targetColor)

            followPost()
        }

    }

    private fun initInfo() {
        val id = intent.getLongExtra("id", -1)

        queryInfoPost(id)

        // 查关注关系
        selectRelationshipPost()
    }


    private val meFollowLauncher = registerForActivityResult(MeFollowContract()) { result ->
    }

    private val meFansLauncher = registerForActivityResult(MeFollowContract()) { result ->
    }

    private fun queryInfoPost(id: Long) {
        try {
            val request = Request.Builder()
                .url(NetworkSettings.USER + "queryHomepageInfo?id=$id")
                .get().build()
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    message.what = ResponseCode.REQUEST_FAILED
                    handler.post {
                        Utils.showMessage(applicationContext, message)
                    }
                    e.printStackTrace()
                }

                override fun onResponse(call: Call, response: Response) {
                    try {
                        if (response.isSuccessful && response.body != null) {
                            val gson = Gson()
                            val responseData = response.body?.string()
                            val jSon = gson.fromJson(responseData, UserHomepageInfoResult::class.java)
                            val info = jSon.data
                            Log.i("日志Homepage onResponse", info.toString())
                            if (info != null) {
                                userInfo = info
                            }

                            handler.post {
                                if (info != null) {
                                    binding.nickname.text = info.nickname
                                    binding.introduction.text = info.intro
                                    binding.followNum.text = info.followToIds?.size.toString()
                                    binding.fansNum.text = info.fansIds?.size.toString()
                                    binding.avatar.setImageBitmap(info.avatar?.let {
                                        ApplicationConst.decodeBase64ToImage(applicationContext,
                                            it
                                        )
                                    })

                                }
                            }

                        } else {
                            message.what = ResponseCode.SERVER_ERROR
                            Log.e("SERVER_ERROR", response.message)
                        }
                    } catch (e: Exception) {
                        message.what = ResponseCode.JSON_SERIALIZATION
                        handler.post {
                            Utils.showMessage(applicationContext, message)
                        }
                        e.printStackTrace()
                    }
                }
            })
        } catch (e: Exception) {
            message.what = ResponseCode.JSON_SERIALIZATION
            Log.i("捕获异常", message.toString())
            e.printStackTrace()
        }
    }


    private fun selectRelationshipPost() {
        try {
            val request = Request.Builder()
                .url(NetworkSettings.USER + "follow?from=${UserConst.id}&to=${userInfo.id}")
                .get().build()
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    message.what = ResponseCode.REQUEST_FAILED
                    handler.post {
                        Utils.showMessage(applicationContext, message)
                    }
                    e.printStackTrace()
                }

                override fun onResponse(call: Call, response: Response) {
                    try {
                        if (response.isSuccessful && response.body != null) {
                            val gson = Gson()
                            val responseData = response.body?.string()
                            val jSon = gson.fromJson(responseData, Result::class.java)
                            val info = jSon.data
                            Log.i("查找关系", info.toString())
                            handler.post {
                                if (info == true) {
                                    isFollow = true
                                    binding.followButton.text = "已关注"
                                    ObjectAnimator.ofArgb(binding.followButton, "backgroundColor", Color.RED).start()
                                } else {
                                    isFollow = false
                                    binding.followButton.text = "关注"
                                    ObjectAnimator.ofArgb(binding.followButton, "backgroundColor", Color.BLUE).start()
                                }
                            }

                        } else {
                            message.what = ResponseCode.SERVER_ERROR
                            Log.e("SERVER_ERROR", response.message)
                        }
                    } catch (e: Exception) {
                        /* message.what = ResponseCode.JSON_SERIALIZATION
                        handler.post {
                            Utils.showMessage(applicationContext, message)
                        } */
                        e.printStackTrace()
                    }
                }
            })
        } catch (e: Exception) {
            message.what = ResponseCode.JSON_SERIALIZATION
            Log.i("捕获异常", message.toString())
            e.printStackTrace()
        }
    }

    private fun followPost() {
        try {
            val request = Request.Builder()
                .url(NetworkSettings.USER + "follow?from=${UserConst.id}&to=${userInfo.id}")
                .delete().build()
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    message.what = ResponseCode.REQUEST_FAILED
                    handler.post {
                        Utils.showMessage(applicationContext, message)
                    }
                    e.printStackTrace()
                }

                override fun onResponse(call: Call, response: Response) {
                    try {
                        if (response.isSuccessful && response.body != null) {
                            val gson = Gson()
                            val responseData = response.body?.string()
                            val jSon =
                                gson.fromJson(responseData, UserHomepageInfoResult::class.java)
                            val info = jSon.data

                        } else {
                            message.what = ResponseCode.SERVER_ERROR
                            Log.e("SERVER_ERROR", response.message)
                        }
                    } catch (e: Exception) {
                        message.what = ResponseCode.JSON_SERIALIZATION
                        handler.post {
                            Utils.showMessage(applicationContext, message)
                        }
                        e.printStackTrace()
                    }
                }
            })
        } catch (e: Exception) {
            message.what = ResponseCode.JSON_SERIALIZATION
            Log.i("捕获异常", message.toString())
            e.printStackTrace()
        }
    }
}
